#!/usr/bin/env python2
#coding:UTF-8
#video_maker.py

import os.path, sys
import cv2
import cv2.cv as cv

DEF_VIDEOFILE = 'castlist.mpg'
DEF_VIDEOCODEC = cv.CV_FOURCC('M','P','E','G')

class Cast_video:
  def __init__(self, settings, filename=None) :
    self.Update_settings(settings)
    self._codec=DEF_VIDEOCODEC
    if filename!=None :
      self.Get_page(filename)
    
  def Update_settings(self,settings) :
    self._fps=settings['VIDEO_FPS']
    self._frames=settings['VIDEO_FRAMES']
    self._framewidth = settings['VIDEO_WIDTH']
    self._frameheight = settings['VIDEO_HEIGHT']
    
  def Get_page( self, filename ) :
    self._pageimg = cv2.imread(filename)
    self._pageheight = len(self._pageimg)
    
  #计算每帧移动多少像素
  def Ypf(self, height=None, frames=None) :
    if frames==None:
      frames=self._frames
    if height==None:
      height=self._pageheight
    delta = (height - self._frameheight) / frames
    return delta
  
  #将每一帧计算出来提取成列表
  def Frame_list(self, ypf=None) :
    if ypf==None :
      ypf=self.Ypf()
    imgs=[]
    height=self._pageheight - self._frameheight
    left=0
    right=self._framewidth
    n=0
    while n<=height :
      up = n
      down = up + self._frameheight
      img = self._pageimg[up:down, left:right]
      imgs.append(img)
      n += ypf
    return imgs
    
  #视频生成函数
  def Render( self, videofile=DEF_VIDEOFILE ) :
    ypf = self.Ypf()
    framelist = self.Frame_list(ypf)
    video = cv2.VideoWriter( videofile, self._codec, self._fps, (self._framewidth,self._frameheight) )
    for frameimg in framelist :
      video.write(frameimg)
    